﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp
{
    /// <summary>
    /// 异步调用
    /// </summary>
    class AsyncCall
    {
        /// <summary>
        /// 定义委托，用于异步调用
        /// </summary>
        private delegate void AsyncMethod();

        /// <summary>
        /// 实际执行的核心方法,调用发送短信
        /// </summary>
        private void SendSMS()
        {
            Console.WriteLine("SendSMS Method Start....");
            //wait 10sec,相当于发送短信耗费了10秒，包括连接接口和短信发送平台
            Thread.Sleep(10000);
            Console.WriteLine("SendSMS Method End......");
        }

        /// <summary>
        /// 使用异步方法调用
        /// </summary>
        private void  AsyncCallMethod()
        {
            Console.WriteLine("Main Method Start....");

            //将需要异步调用的方法委托给创建的AsyncMethod，不用等待SendSMS执行结束，当前线程继续往下执行
            AsyncMethod async = new AsyncMethod(this.SendSMS);
            async.BeginInvoke(null,null);

            Console.WriteLine("Main Method End......");
        }

        /// <summary>
        /// 使用同步方法调用
        /// </summary>
        private void SyncCallMethod()
        {
            Console.WriteLine("Main Method Start....");

            //当前线程一致等待SendSMS方法执行
            SendSMS();

            Console.WriteLine("Main Method End......");
        }

        public static void Test()
        {
            AsyncCall test = new AsyncCall();

            Console.WriteLine("测试同步调用");
            //测试同步调用
            test.SyncCallMethod();


            Console.WriteLine("测试异步调用");
            test.AsyncCallMethod();
        }

        /**
         * 测试结果
         * 
            测试同步调用
            Main Method Start....
            Async Method Start....
            Async Method End......
            Main Method End......
            测试异步调用
            Main Method Start....
            Main Method End......
            Async Method Start....
            Async Method End......

         * 
         * 
         * 
         * 
         * 
         * 
         * 
         */
    }
}
